//
//  ShortAudioPlayer.swift
//  PlayMp3
//
//  Created by ZhouJiatao on 2019/3/23.
//  Copyright © 2019 eighteye. All rights reserved.
//

import Foundation
import AVFoundation

/// 注意ARC回收机制。把ShortAudioPlayer保存于成员变量。
public class ShortAudioPlayer: NSObject {
    
    private var player: AVAudioPlayer?
    
    /// 播放保存在应用内部的音频文件
    public func playInternalSound(named: String, onBundle: Bundle = Bundle.main, withExtension ext: String = ".mp3") {
        if isEmpty(named) { return }
        
        let url = onBundle.url(forResource: named, withExtension: ext)
        
        // 调试用
//        if url == nil {
//            print("找不到音频文件")
//            url = onBundle.url(forResource: "找不到音频文件", withExtension: ".mp3")
//        }
    
        guard let validUrl = url else {
            return
        }
        
        do {
            player = try AVAudioPlayer(contentsOf: validUrl)
            player?.play()
        } catch {
            print(error)
        }
    }
}
